package tech.kunyuan.controller;

import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * Description:
 *
 * @Author: ky
 * DateTime: 2022-10-20 11:46
 */

@RestController
@RequestMapping("/mq")
public class MqProducerController {

    @GetMapping("/p1")
    public void Porducer() throws Exception
    {
        // 实例化消息生产者Producer
        DefaultMQProducer producer = new DefaultMQProducer("please_rename_unique_group_name");
        // 设置NameServer的地址
        //producer.setNamesrvAddr(env.getProperty("rocket.host"));
        producer.setNamesrvAddr("localhost:19876");
        //producer.setNamesrvAddr("localhost:9876");
        // 启动Producer实例
        producer.start();
        int messageCount = 10000;//发送消息数量
        for (int i = 0; i < messageCount; i++) {
            // 创建消息，并指定Topic，Tag和消息体
            Message msg = new Message("TopicTest" /* Topic */,
                    "TagA" /* Tag */,
                    ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET) /* Message body */
            );
            // 发送消息到一个Broker
            SendResult sendResult = producer.send(msg);
            // 通过sendResult返回消息是否成功送达
            System.out.printf("%s%n", sendResult);
        }
        // 如果不再发送消息，关闭Producer实例。
        //Thread.sleep(3000);
        //final CountDownLatch countDownLatch = new CountDownLatch(messageCount);//定义条件
        //countDownLatch.await(5, TimeUnit.SECONDS);//达到100关闭生产（发送者）
        producer.shutdown();

    }
}
